#include "SList.h"

SLN* BuySListNode(SLTDataType x) {
	SLN* plist = (SLN*)malloc(sizeof(SLN));
	plist->data = x;
	plist->next = NULL;

	return plist;
}

void SListPrint(SLN* phead) {
	SLN* cur = phead;
	while (cur != NULL) {
		printf("%d ", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

void SListPushBack(SLN** pphead, SLTDataType x) {
	SLN* ans = BuySListNode(x);
	if (*pphead == NULL) {
		*pphead = ans;
	}
	else {
		SLN* tail = *pphead;
		while (tail->next != NULL) {
			tail = tail->next;
		}
		tail->next = ans;
	}
}

void SListPushFront(SLN** pphead, SLTDataType x) {
	SLN* ans = BuySListNode(x);
	ans->next = *pphead;
	*pphead = ans;
}

void SListPopFront(SLN** pphead) {
	SLN* ans = (*pphead)->next;
	free(*pphead);
	*pphead = ans;
}

void SListPopBack(SLN** pphead) {

	if (*pphead == NULL) {
		return;
	}
	else if ((*pphead)->next = NULL) {
		free(*pphead);
		*pphead = NULL;
	}
	else {
		SLN* tail = (*pphead)->next;
		SLN* prev = *pphead;
		while (tail->next != NULL) {
			prev = tail;
			tail = tail->next;
		}
		free(tail);
		prev->next = NULL;
	}
}

SLN* FindSList(SLN* phead, SLTDataType x) {
	SLN* plist = phead;
	while (plist != NULL) {
		if (plist->data == x)
			return plist;
		plist = plist->next;
	}
	return NULL;
}

void SListInsertFront(SLN** phead, SLN* pos, SLTDataType x) {
	if (pos == *phead) {
		SListPushFront(phead, x);
	}
	else {
		SLN* tmp = *phead;
		while (tmp->next != pos) {
			tmp = tmp->next;
		}
		SLN* res = BuySListNode(x);
		res->next = pos;
		tmp = res;
		free(pos);
	}
}
void SListErase(SLN** phead, SLN* pos) {
	if (pos == *phead) {
		SListPopFront(phead);
	}
	else {
		SLN* prev = *phead;
		while (prev->next != pos) {
			prev = prev->next;
		}
		prev->next = pos->next;
		free(pos);
	}
}